package cn.aopmin.handler;

import cn.aopmin.utils.UserContextHolder;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatisPlus实现自动填充数据库表中的字段值
 * @author 白豆五
 * @since 2025/3/12
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start mp insert field fill ....");
        // 注: 这里的字段名 必须和实体类中的字段名一致
        this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject, "createdBy",  Long.class,UserContextHolder.getUserId());
        this.strictInsertFill(metaObject, "updatedBy",  Long.class,UserContextHolder.getUserId());
    }

    // 更新时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start mp update field fill ....");
        this.strictInsertFill(metaObject, "updatedBy",  Long.class,UserContextHolder.getUserId());
        this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class,LocalDateTime.now());
    }
}